var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var config=require('../config');
var User=require('./user')
var Post=require('./post')
var db=mongoose.createConnection(config.db_url);
db.on('error',function(error){
    console.log(error);
});
db.model('User',User.userSchema);
db.model('Post',Post.postSchema);
var replySchema=new Schema({
    replyUser:{type:Schema.Types.ObjectId,ref:'User'},
    replyPost:{type:Schema.Types.ObjectId,ref:'Post'},
    //secondReplyTotal:{type:Number,default:0},
//    toUser:{type:Schema.Types.ObjectId,ref:'User'},
//    toReply:{type:Schema.Types.ObjectId,ref:'Reply'},
    content:String,
    state:{type:Number,default:0},
    replyDate:{type:Date,default:Date.now}
});
//users---对应数据库表名
var Reply=db.model('Reply',replySchema);
Reply.prototype.findReplyByOption=function (options,callback){
    Reply.find(options).populate('replyUser').exec(function(err,datas){
        callback(err,datas);
    })

}
Reply.prototype.updateSecondReplyTotalById=function (id,callback){
    Reply.update({_id:id},{'$inc':{secondReplyTotal:1}},function(err){
        callback(err);
    })
}
Reply.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=Reply.find(q,col).sort('replyDate').sort('-replyDate').skip(obj.page.skipFrom).limit(obj.page.limit).populate('replyUser toUser toReply replyPost');
    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            Reply.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    callback(null, count,pageCount, datas);
                }
            });
        }
    });

}
module.exports = Reply;
module.exports.replySchema=replySchema;
